package com.wang.interview.tests.threadtest;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author: wang
 * @date: 2021/8/12 15:03
 * @description: 自旋锁模拟
 */

public class T3 {
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void m1(){
        // 获取当前线程
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+"开始1");
        while (!atomicReference.compareAndSet(null, thread)){            // 相当于线程上锁
            // 如果当前线程对应 CAS 不是 null ，条件为真进入 while 自旋              // 循环，让后来的线程相当于阻塞
        }
        System.out.println(thread.getName()+"结束1");
    }

    public void m2(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+"开始2");
        //try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        // 如果当前线程对应 CAS 不是 null，更改为 null
        atomicReference.compareAndSet(thread, null);                       // 相当于线程释放锁
        System.out.println(thread.getName()+"结束2");
    }

    public static void main(String[] args) {
        T3 t3 = new T3();
        new Thread(()->{
            t3.m1();
            try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
            t3.m2();
        },"a").start();
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        new Thread(()->{
            t3.m1();
            t3.m2();
        },"b").start();
    }

}
